package com.hirain.zookeeper.zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.BytesPushThroughSerializer;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.util.List;

/**
 * Created by caicf on 2016/8/31.
 */
public class ZKClient {

    @Test
    public void test() {
        ZkClient client=new ZkClient("127.0.0.1:2181",1000,1000,new SerializableSerializer());
        User user=new User();
        user.setName("zookeeperName");
        //节点路径，节点数据，数据类型    返回节点成功创建后的路径
        String path=client.create("/caicf",user, CreateMode.PERSISTENT);
    }

    @Test
    public void test1() {
        ZkClient client=new ZkClient("127.0.0.1:2181",1000,1000,new SerializableSerializer());
        //获取节点的信息
        Stat stat=new Stat();
        User user = client.readData("/caicf",stat);
        System.out.println(user.getName());
        System.out.println(stat);
    }

    @Test
    public void test2() {
        ZkClient client=new ZkClient("127.0.0.1:2181",1000,1000,new SerializableSerializer());
        //获取子节点的信息
        List<String> chList=client.getChildren("/caicf");
        //检测节点是否存在
        boolean isExists=client.exists("/caicf");
        //删除没有子节点的节点
        boolean deleteNode=client.delete("/caicf");
        //删除含有子节点的节点
        boolean deleteNodeWithChild = client.deleteRecursive("/caicf");
    }


    @Test
    public void testcreate() {
        ZkClient client=new ZkClient("127.0.0.1:2181",1000,1000,new BytesPushThroughSerializer());
        //节点数据的修改
        User user=new User();
        user.setName("fxd");
        client.writeData("/caicf",user);
        client.subscribeDataChanges("/caicf", new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }

            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });
    }
}
